package com.imooc.distributedemo.resume.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * leetcode03  无重复字符的最长子串
 */
public class Solution03 {
    public static void main(String[] args) {
        String s = "abcabcbb";
        int result = lengthOfLongestSubstring(s);
        System.out.println(result);
    }

    private static int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        // 使用HashMap来存储字符及其索引
        Map<Character, Integer> map = new HashMap<>();
        int maxLength = 0;
        int left = 0;

        for (int right = 0; right < s.length(); right++) {
            char currentChar = s.charAt(right);

            // 如果字符已经存在于map中，且其索引不小于left
            if (map.containsKey(currentChar) && map.get(currentChar) >= left) {
                // 更新left为重复字符的下一个索引
                left = map.get(currentChar) + 1;
            }

            // 更新字符的索引
            map.put(currentChar, right);

            // 更新最长不重复子串的长度
            maxLength = Math.max(maxLength, right - left + 1);
        }

        return maxLength;
    }
}
